package com.forum.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.forum.article.entity.ForumArticle;
import com.forum.article.entity.ForumArticleTag;
import com.forum.article.entity.ForumArticleTagMap;
import com.forum.article.mapper.ForumArticleMapper;
import com.forum.article.mapper.ForumArticleTagMapMapper;
import com.forum.article.mapper.ForumArticleTagMapper;
import com.forum.article.service.ForumArticleTagMapService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bncgnc
 * @since 2022-01-04
 */
@Service
public class ForumArticleTagMapServiceImpl extends ServiceImpl<ForumArticleTagMapMapper, ForumArticleTagMap> implements ForumArticleTagMapService {
    @Autowired
    private ForumArticleTagMapMapper forumArticleTagMapMapper;
    @Autowired
    private ForumArticleTagMapper forumArticleTagMapper;
    @Autowired
    private ForumArticleMapper forumArticleMapper;


    /**
     * 通过文章id查询文章所有的标签(中间表查询)
     * @param articleId
     * @return
     */
    @Override
    public List<ForumArticleTag> findAllTagsById(Long articleId) {
        List<ForumArticleTagMap> articleTagMap = forumArticleTagMapMapper.selectList(
                    new QueryWrapper<ForumArticleTagMap>()
                    .eq("article_id", articleId));

        if ( articleTagMap != null && articleTagMap.size() > 0 ) {
            List<Long> tagIds = articleTagMap.stream().map(at -> at.getArticleTagId()).collect(Collectors.toList());

            List<ForumArticleTag> forumArticleTags = forumArticleTagMapper.selectBatchIds(tagIds);

            forumArticleTags.stream().forEach(System.out::println);

            return forumArticleTags;
        } else {
            return null;
        }
    }

    /**
     * 通过标签id查询对应的文章(中间表查询)
     * @param tagId
     * @return
     */
    @Override
    public List<ForumArticle> findForumArticleByTagId(Long tagId) {
        List<ForumArticleTagMap> articleTagMap = forumArticleTagMapMapper.selectList(
                new QueryWrapper<ForumArticleTagMap>()
                        .eq("article_tag_id", tagId));

        if ( articleTagMap != null && articleTagMap.size() > 0 ) {
            List<Long> articleIds = articleTagMap.stream().map(at -> at.getArticleId()).collect(Collectors.toList());

            // 通过多个id批量查询
            return forumArticleMapper.selectBatchIds(articleIds);
        } else {
            return null;
        }
    }
}
